package com.hfzy.ihk.common.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.sound.midi.Soundbank;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 文件工具类
 * @author wws
 *
 */
public class FileUtils {
	private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
	/**
	 * 传入文件夹路径，该方法能够实现创建整个路径
	 * @param filePath 文件夹路径，不包含文件名称及后缀名
	 */
	public static void checkAndCreateDir(String filePath){
		File file = new File(filePath);
		// 如果路径不存在,则创建
		if (!file.getParentFile().exists()) {
			file.mkdirs();
		}else {
			if(!file.exists())
				file.mkdir();
		}
	}

	public static void copyFile(String src,String dest) throws Exception {
		File fileSrc = new File(src);
		if(!fileSrc.exists()) {
			System.out.println("not exists:"+src);
			return;
		}
		File file = new File(dest);
		if(!file.exists())
			file.createNewFile();

		FileInputStream in = new FileInputStream(fileSrc);
		FileOutputStream out = new FileOutputStream(file);

		int c;
		byte buffer[]=new byte[1024];
		while((c=in.read(buffer))!=-1){
			for(int i=0;i<c;i++)
				out.write(buffer[i]);
		}
		in.close();
		out.close();
	}

	/**
	 * 通过HTTP方式获取文件
	 *
	 * @param strUrl
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static boolean getRemoteFile(String strUrl, String fileName) throws IOException {
		URL url = new URL(strUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		DataInputStream input = new DataInputStream(conn.getInputStream());
		DataOutputStream output = new DataOutputStream(new FileOutputStream(fileName));
		byte[] buffer = new byte[1024 * 8];
		int count = 0;
		while ((count = input.read(buffer)) > 0) {
			output.write(buffer, 0, count);
		}
		output.close();
		input.close();
		return true;
	}

	public static void renameFile(String path,String oldname,String newname){
		if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名
			File oldfile=new File(path+"/"+oldname);
			File newfile=new File(path+"/"+newname);
			if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同，则不允许重命名
				System.out.println(newname+"已经存在！");
			else{
				oldfile.renameTo(newfile);
			}
		}
	}

	public static void changeDirectory(String filename,String oldpath,String newpath,boolean cover){
		if(!oldpath.equals(newpath)){
			File oldfile=new File(oldpath+"/"+filename);
			File newfile=new File(newpath+"/"+filename);
			if(newfile.exists()){//若在待转移目录下，已经存在待转移文件
				if(cover)//覆盖
					oldfile.renameTo(newfile);
				else
					System.out.println("在新目录下已经存在："+filename);
			}
			else{
				oldfile.renameTo(newfile);
			}
		}
	}

	public String BufferedReaderDemo(String path) throws Exception{
		File file=new File(path);
		if(!file.exists()||file.isDirectory())
			throw new FileNotFoundException();
		BufferedReader br=new BufferedReader(new FileReader(file));
		String temp=null;
		StringBuffer sb=new StringBuffer();
		temp=br.readLine();
		while(temp!=null){
			sb.append(temp+" ");
			temp=br.readLine();
		}
		return sb.toString();
	}

	/**
	 * 获得指定文件的byte数组
	 */
	public static byte[] getBytes(File file) throws IOException {

		if(file==null || !file.exists()) {
			System.out.println("文件不存在，path:"+file.getAbsolutePath());
			return null;
		}
		FileInputStream fis=null;
		ByteArrayOutputStream bos=null;
		byte[] buffer = null;
		try {
			fis = new FileInputStream(file);
			bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(fis!=null) {
				fis.close();
			}
			if(bos!=null) {
				bos.close();
			}
		}
		return buffer;
	}
	/**
	 * 获得指定文件的byte数组
	 */
	public static byte[] getBytes_1(File file) throws IOException {

		FileInputStream inputStream=null;
		byte[] bytes = null;
		try {
			inputStream = new FileInputStream(file);
			bytes = new byte[inputStream.available()];
			if(bytes.length==0) {
				System.out.println("----------------------error---------文件没内容--------------------------");
				return null;
			}
			inputStream.read(bytes);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(inputStream!=null)
				inputStream.close();
		}
		return bytes;
	}
	/**
	 * 获得指定文件的byte数组
	 */
	public static byte[] getBytes(String filePath){
		byte[] buffer = null;
		try {
			File file = new File(filePath);
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			buffer = bos.toByteArray();
			fis.close();
			bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	public static void createFile(String path,String filename) throws IOException{
		File file=new File(path+"/"+filename);
		if(!file.exists())
			file.createNewFile();
	}

	public static void delFile(String path,String filename){
		File file=new File(path+"/"+filename);
		if(file.exists()&&file.isFile())
			file.delete();
	}

	public static String uploadFilePic(MultipartFile file, String name, String filePath) throws Exception {
		String fileName = "";
		FileChannel foChannel = null;
		File f = new File(filePath);
		if (!f.exists()) {
			f.mkdirs();
		} else {
			if (!f.isDirectory()) {
				f.mkdirs();
			}
		}
		String filelastname = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		fileName = filePath + "/" + name + filelastname;
		//nio上传
		foChannel = new FileOutputStream(fileName).getChannel();
		ByteBuffer src = ByteBuffer.wrap(file.getBytes());
		foChannel.write(src);
		if (foChannel != null) {
			foChannel.close();
		}
		return fileName;
	}

	/**
	 * 保存文件
	 *
	 * @param file 要保存的文件
	 * @param name 新文件名
	 * @param filePath 保存地址
	 *                 仅用来接收amr录音文件
	 * @return
	 */
	public static String uploadFile(MultipartFile file, String name, String filePath,String type) throws Exception {
		String fileName = "";
		FileChannel foChannel = null;
			File f = new File(filePath);
			if (!f.exists()) {
				f.mkdirs();
			} else {
				if (!f.isDirectory()) {
					f.mkdirs();
				}
			}
//			String filelastname = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			fileName = filePath + "/" + name + "."+type;


			//nio上传
			foChannel = new FileOutputStream(fileName).getChannel();
			ByteBuffer src = ByteBuffer.wrap(file.getBytes());

			foChannel.write(src);
			if (foChannel != null) {
				foChannel.close();
			}
		return fileName;
	}


	public static String getUrlByPath(String path,String Profile){
		if("pro".equals(Profile)){

			return "";
		}else if("local".equals(Profile)){
			return path.replace("F:/czs/work/hfzy-linkcall/web-call-data/src/main/resources/","http://172.16.6.102:7770/calldata/");

		}else{
			return path;
		}
	}


	/**
	 * 转化成pcm文件
	 * @param      profile      ffmpeg 的 bin
	 * @param      sourcePath  被转化文件
	 * @param      targetPath  转化的文件
	 * @return     targetPath    如果返回空，说明是异常
	 * */
	public static  String changeVioceFileToPcm(String profile,String sourcePath, String targetPath) throws Exception {
		logger.info("changeVioceFileToPcm[转化音频文件为 PCM格式 ]:{},{},{}",profile,sourcePath,targetPath);
		String webroot = "G:\\ffmpeg-20161208-3ab1311-win64-static\\ffmpeg-20161208-3ab1311-win64-static\\bin";
		if("pro".equals(profile)){
			//正式机环境下 待定
			webroot = "G:\\ffmpeg-20161208-3ab1311-win64-static\\ffmpeg-20161208-3ab1311-win64-static\\bin";
		}else if("local".equals(profile)){
			File filePath = new File("/usr/bin");
			webroot = filePath.getAbsolutePath();
			System.out.println(webroot);
		}
		Runtime run = null;
		try {
			run = Runtime.getRuntime();
			long start=System.currentTimeMillis();
			System.out.println(CommonUtils.execCommand(new File(webroot).getAbsolutePath()+"/ffmpeg -y -i "+sourcePath+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+targetPath));
			long end=System.currentTimeMillis();
			logger.info(sourcePath+" convert success, costs:"+(end-start)+"ms");
		} catch (Exception e) {
			targetPath = "";
			e.printStackTrace();
			logger.error("转化异常？？？？？",e);
		}finally{
			//run调用lame解码器最后释放内存
			run.freeMemory();
		}
		return targetPath;
	}


}
